package com.school.base.action.admin;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.school.base.model.Admin;
import com.school.base.model.News;
import com.school.base.service.NewsService;
import com.school.common.base.BaseAction;
import com.school.common.constant.Constant;
import com.school.common.util.FileUtils;
import com.school.common.util.SpringUtils;
import com.school.common.util.StringUtils;
import com.school.common.util.SystemConfUtils;

public class NewsAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6380642678118390970L;
	private static Logger logger = Logger.getLogger(NewsAction.class);
	private static NewsService service = (NewsService) SpringUtils.getBean("base_newsService");
	private News news;
	private List<News> newsList;
	private File imgFile;
	private String imgFileFileName;

	public String getImgFileFileName() {
		return imgFileFileName;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	public File getImgFile() {
		return imgFile;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	public List<News> getNewsList() {
		return newsList;
	}

	public void setNewsList(List<News> newsList) {
		this.newsList = newsList;
	}

	public String list() {
		newsList = service.getNewsList(news, pageBean);
		return SUCCESS;
	}

	public String edit() {
		if (news != null && news.getId() > 0) {
			news = service.getNewsById(news.getId());
		}
		if (news == null) {
			news = new News();
		}
		return SUCCESS;
	}

	public String editDo() {
		if ("POST".equals(this.getHttpServletRequest().getMethod())) {
			if (news != null) {
				if (news.getId() > 0) {
					try {
						service.updateNews(news);
						logger.info("Update news.");
					} catch (Exception e) {
						this.addActionError(e.getMessage());
						return INPUT;
					}
				} else {
					Admin admin = (Admin) this.getHttpSession().getAttribute(Constant.SESSION_KEY_ADMIN);
					if (admin != null) {
						try {
							service.insertNews(news, admin.getId());
							logger.info("Insert news.");
						} catch (Exception e) {
							this.addActionError(e.getMessage());
							return INPUT;
						}
					} else {
						logger.info("Not save news:Admin object is null.");
					}
				}
			} else {
				logger.info("Not save news:news object is null.");
			}
		} else {
			logger.info("Not save news:the request method is not 'post'.");
		}
		return SUCCESS;
	}

	public String delete() {
		if (news != null && news.getId() > 0) {
			service.deleteNews(news.getId());
			logger.info("Delete news.");
		} else {
			logger.info("Not delete news:news's id is null.");
		}
		return SUCCESS;
	}

	public String sticky() {
		if (news != null && news.getId() > 0) {
			int to = news.getSticky() == 1 ? 0 : 1;
			service.updateNewsSticky(news.getId(), to);
			logger.info("Update news's sticky.");
		} else {
			logger.info("Not top news:news's id is null.");
		}
		return SUCCESS;
	}

	public void upload() throws IOException {
		if (imgFile != null) {
			HttpServletResponse response = this.getHttpServletResponse();
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			String ext = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
			String allowTypes = SystemConfUtils.getProperty("system.fileUpload.image.type");
			JSONObject json = new JSONObject();
			if (("," + allowTypes + ",").indexOf("," + ext.substring(1) + ",") == -1) {
				json.put("error", 1);
				json.put("message", "文件格式不正确，请选择后缀名为(" + allowTypes + ")的文件");
				response.getWriter().print(json);
				return;
			}
			int maxLength = Integer.parseInt(SystemConfUtils.getProperty("system.fileUpload.image.maxSize"));
			if (imgFile.length() > maxLength) {
				json.put("error", 1);
				json.put("message", "文件过大，请上传小于" + StringUtils.byteUnitTrans(maxLength) + "的文件");
				response.getWriter().print(json);
				return;
			}
			String filePath = "\\upload\\news\\images\\";
			String imgBaseUrl = SystemConfUtils.getProperty("system.fileUpload.baseUrl");
			String imgDir = this.getServletContext().getRealPath("/") + filePath;
			String fileName = (new Date()).getTime() + ext;
			String fileUrl = imgBaseUrl + filePath.replace("\\", "/") + fileName;
			try {
				FileUtils.saveFile(imgFile, imgDir + fileName);
				json.put("error", 0);
				json.put("url",fileUrl);
				response.getWriter().print(json);
			} catch (IOException e) {
				logger.error(e.getMessage());
				json.put("error", 1);
				json.put("message", e.getMessage());
				response.getWriter().print(json);
			}
		}
	}
}
